#include "Htpasswd.h"

#define SETPASSWORDARGS 4

void IronSvn::Htpasswd::SetPassword(String^ file, String^ user, String^ password)
{
	if (String::IsNullOrEmpty(file))
	{
		throw gcnew ArgumentNullException("file");
	}
	else if (String::IsNullOrEmpty(user))
	{
		throw gcnew ArgumentNullException("user");
	}
	else if (String::IsNullOrEmpty(password))
	{
		throw gcnew ArgumentNullException("password");
	}

	if (file->Length >= MAX_STRING_LEN - 1)
	{
		throw gcnew ArgumentOutOfRangeException("File name exceeds maximum length " + MAX_STRING_LEN);
	}
	else if (user->Length >= MAX_STRING_LEN - 1)
	{
		throw gcnew ArgumentOutOfRangeException("User name exceeds maximum length " + MAX_STRING_LEN);
	}
	else if (password->Length >= MAX_STRING_LEN - 1)
	{
		throw gcnew ArgumentOutOfRangeException("Password exceeds maximum length " + MAX_STRING_LEN);
	}

	char* cfile = (char*)(Marshal::StringToHGlobalAnsi(file)).ToPointer();
	try
	{
		char* cuser = (char*)(Marshal::StringToHGlobalAnsi(user)).ToPointer();
		try
		{
			char* cpassword = (char*)(Marshal::StringToHGlobalAnsi(password)).ToPointer();
			try
			{
				set_password(cfile, cuser, cpassword, !File::Exists(file), false);
			}
			finally
			{
				Marshal::FreeHGlobal(IntPtr((void*)cpassword));
			}
		}
		finally
		{
			Marshal::FreeHGlobal(IntPtr((void*)cuser));
		}
	}
	finally
	{
		Marshal::FreeHGlobal(IntPtr((void*)cfile));
	}
}

void IronSvn::Htpasswd::RemoveUser(String^ file, String^ user)
{
	if (String::IsNullOrEmpty(file))
	{
		throw gcnew ArgumentNullException("file");
	}
	else if (String::IsNullOrEmpty(user))
	{
		throw gcnew ArgumentNullException("user");
	}

	if (file->Length >= MAX_STRING_LEN - 1)
	{
		throw gcnew ArgumentOutOfRangeException("File name exceeds maximum length " + MAX_STRING_LEN);
	}
	else if (user->Length >= MAX_STRING_LEN - 1)
	{
		throw gcnew ArgumentOutOfRangeException("User name exceeds maximum length " + MAX_STRING_LEN);
	}

	char* cfile = (char*)(Marshal::StringToHGlobalAnsi(file)).ToPointer();
	try
	{
		char* cuser = (char*)(Marshal::StringToHGlobalAnsi(user)).ToPointer();
		try
		{
			set_password(cfile, cuser, nullptr, !File::Exists(file), true);
		}
		finally
		{
			Marshal::FreeHGlobal(IntPtr((void*)cuser));
		}
	}
	finally
	{
		Marshal::FreeHGlobal(IntPtr((void*)cfile));
	}
}
